import moment from 'moment';


//JSON深度合并、数组一一对应且数组内对象保留原来的Key
export function mergeJSON(target, source) {
    // Iterate through all properties in the source object
    for (let key in source) {
        if (source.hasOwnProperty(key)) {
            if (target.hasOwnProperty(key)) {
                if (Array.isArray(source[key]) && Array.isArray(target[key])) {
                    // If both properties are arrays, merge them
                    target[key] = mergeArrays(target[key], source[key]);
                } else if (typeof source[key] === 'object' && typeof target[key] === 'object') {
                    // If both properties are objects, recursively merge them
                    target[key] = mergeJSON(target[key], source[key]);
                } else {
                    // Otherwise, overwrite the target property with the source property
                    target[key] = source[key];
                }
            } else {
                // If the target object does not have this property, add it
                target[key] = source[key];
            }
        }
    }
    return target;
}

function mergeArrays(target, source) {
    // Make a copy of the target array
    let result = target.slice(0);
    // Iterate through all elements in the source array
    source.forEach(function(item, index) {
        if (typeof item === 'object' && typeof result[index] === 'object') {
            // If both elements are objects, recursively merge them
            result[index] = mergeJSON(result[index], item);
        } else {
            // Otherwise, overwrite the target element with the source element
            result[index] = item;
        }
    });
    return result;
}


export function formatDate(date) {
    let year = date.getFullYear();
    let month = ('0' + (date.getMonth() + 1)).slice(-2);
    let day = ('0' + date.getDate()).slice(-2);
    let hours = ('0' + date.getHours()).slice(-2);
    let minutes = ('0' + date.getMinutes()).slice(-2);
    let seconds = ('0' + date.getSeconds()).slice(-2);
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function isNumber(value) {
    return typeof value === 'number' && !isNaN(value);
}


function deepMerge(target, source) {
    if (typeof target !== 'object' || typeof source !== 'object') return source;
    for (const key in source) {
        if (source[key] === null && (target[key] === undefined || target[key] === null)) {
            target[key] = null;
        } else if (source[key] instanceof Array) {
            target[key] = (target[key] || []).concat(source[key]);
        } else if (typeof source[key] === 'object') {
            target[key] = deepMerge(target[key] || {}, source[key]);
        } else {
            target[key] = source[key];
        }
    }
    return target;
}


// export function y_auto_function(y) {
//     return y //放大范围在 后台py已处理 0.05
//     console.log('y_auto_function')
//     if (!isNumber(y['max'])) {
//         y["max"] = function(value) {
//             var number = value.max + (value.max - value.min) * 0.01; // 上部空白区域
//             return number.toFixed(y['pcs'])
//         };
//     } else {
//         // y["max"] *= 1.1;
//     }
//     if (!isNumber(y['min'])) {
//         y["min"] = function(value) {
//             var number = value.min - (value.max - value.min) * 0.01; // 下部空白区域
//             return number.toFixed(y['pcs'])
//         };
//     } else {
//         // y["min"] *= 1.1;
//     }
//     return y
// }

export function compareTimeRange(time1, time2) {
    const date1 = new Date(time1);
    const date2 = new Date(time2);

    const timestamp1 = date1.getTime();
    const timestamp2 = date2.getTime();

    const timeDiff = Math.abs(timestamp2 - timestamp1);
    const hoursDiff = timeDiff / (1000 * 60 * 60);

    return hoursDiff <= 10;
}



/**
 * 格式化时间数组数据
 * @param {Array} data - X轴时间数据数组
 * @param {string} lang - 语言代码 ('en' 或 'zh')
 * @returns {Array} 格式化后的时间数组
 */
export function formatTimeData(data, lang) {
    const outputFormat = lang === 'en' ? 'DD/MM/YYYY HH:mm:ss' : 'YYYY-MM-DD HH:mm:ss';
    const inputFormat = 'YYYY-MM-DD HH:mm:ss'; // 指定输入格式
    moment.locale(lang === 'zh' ? 'zh-cn' : 'en');

    if (Array.isArray(data)) {
        if (data[0] && typeof data[0] === 'string') {
            return data.map(time => {
                // 使用指定的输入格式解析时间
                const m = moment(time, inputFormat);
                return m.isValid() ? m.format(outputFormat) : time;
            });
        } else if (data[0] && Array.isArray(data[0])) {
            return data.map(item => {
                const m = moment(item[0], inputFormat);
                return [m.isValid() ? m.format(outputFormat) : item[0], item[1]];
            });
        }
    }
    return data;
}

/**
 * 处理数据配置中的时间格式
 * @param {Object} data - 数据配置对象
 * @param {string} lang - 语言代码
 */
export function processTimeData(data, lang) {
    if (!data) return;

    if (data.xAxis && data.xAxis[0] && Array.isArray(data.xAxis[0].data)) {
        data.xAxis[0].data = formatTimeData(data.xAxis[0].data, lang);
    } else if (data.xAxis && Array.isArray(data.xAxis.data)) {
        data.xAxis.data = formatTimeData(data.xAxis.data, lang);
    }
}



/**
 * 格式化单个时间值
 * @param {string} time - 时间字符串
 * @param {string} lang - 语言代码
 * @returns {string} 格式化后的时间字符串
 */
export function formatSingleTime(time, lang) {
    const outputFormat = lang === 'en' ? 'DD/MM/YYYY HH:mm:ss' : 'YYYY-MM-DD HH:mm:ss';
    const inputFormat = 'YYYY-MM-DD HH:mm:ss';

    const m = moment(time, inputFormat);
    return m.isValid() ? m.format(outputFormat) : time;
}

/**
 * 处理表格数据中的时间列
 * @param {Array} data - 表格数据数组
 * @param {string} lang - 语言代码
 * @param {string} timeField - 时间字段名，默认为 'RecordTime'
 * @returns {Array} 处理后的数据
 */
export function processTableTimeData(data, lang, timeField = 'RecordTime') {
    if (!Array.isArray(data)) return data;

    return data.map(row => ({
        ...row,
        [timeField]: formatSingleTime(row[timeField], lang)
    }));
}